import React, { Component } from 'react';
import { getMultiLang, createPage, cardCache, toast, viewModel, promptBox } from 'nc-lightapp-front';
import ApprovalTrans from 'uap/common/components/approvalTrans';
import _ from 'lodash-es';
import config from './config';
import {
    onSearchButtonClick,
    onPageButtonClick,
    onTablePageChange,
    onTableInnerButtonClick,
    onTableSelectChange,
    onTableRowDoubleClick
} from './events';
import api from '../../common/api';

const { setDefData, getDefData } = cardCache;

class Page extends Component {
    constructor(props) {
        super(props);
        props.use.search(config.headcode);
        props.use.table(config.bodycode);
        props.use.table(config.tradetypecode);
        this.state = {
            multiLang: {},
            tradeType: '',
            tradeTypeName: '',
            isInspectionShowed: false,
            inspectionSourceData: {},
            // 联查费用申请单
            isLinkQueryFysqModelShowed: false,
            linkQueryFysqModelSourceData: {},
            // 联查费用预提单
            isLinkQueryFyytModelShowed: false,
            linkQueryFyytModelSourceData: {},
            // 联查借款单
            isLinkQueryJkbxModelShowed: false,
            linkQueryJkbxModelSourceData: { tradetype: '' },
            // 联查审批情况
            isApproveDetailShowed: false,
            approveDetailSourceData: {},
            // 审批指派
            isApprovalTransShowed: false,
            approvalTransSourceData: {}
        };
        // TODO 缓存多语
    }

    componentDidMount() {
        this.initTempAndLang();
    }

    initTempAndLang() {
        const props = this.props;
        getMultiLang({
            ...config.multiLang,
            callback: json => {
                this.setState({ multiLang: json }, () => {
                    props.createUIDom({ pagecode: config.pagecode }, data => {
                        console.log('=====template', data);
                        this.setButton(data.button);
                        this.setMeta(data.template, data);
                    });
                });
            }
        });
    }

    setMeta(meta, all) {
        const props = this.props;

        this.setState({
            tradeType: _.get(all, 'context.paramMap.transtype', ''),
            tradeTypeName: _.get(all, 'context.paramMap.transtype_name', '')
        });

        meta[config.headcode].items.forEach(item => {
            if (item.attrcode === 'pk_tradetypeid') {
                item.queryCondition = function () {
                    return {
                        GridRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.ErmTranstypeRefSqlBuilder'
                    };
                };
            } else if (item.attrcode === 'pk_org') {
                item.queryCondition = function () {
                    return {
                        TreeRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.OrgTreeRefSqlBuilder',
                        DataPowerOperationCode: 'fi',
                        isDataPowerEnable: 'Y'
                    };
                };
            }
        });

        meta[config.bodycode].pagination = true;
        meta[config.bodycode].pageInfo = {
            pageSize: config.pageSize
        };

        const tableInnerButtons = props.button
            .getButtons()
            .filter(item => item.area === config.innerButtonArea)
            .map(item => item.key);

        meta[config.bodycode].items.push({
            label: this.state.multiLang['opr_title'],
            itemtype: 'customer',
            attrcode: 'opr',
            width: '140px',
            visible: true,
            fixed: 'right',
            render: (text, record, index) => {
                const spzt = _.get(record, 'spzt.value', '');
                const djzt = _.get(record, 'djzt.value', '');
                const red_status = _.get(record, 'red_status.value', '');
                const tradeType = _.get(record, 'djlxbm.value', '');

                return props.button.createOprationButton(
                    tableInnerButtons.filter(item => {
                        if (item === 'table_inner_edit' && (spzt !== '-1' || djzt === '-1')) {
                            return false;
                        } else if (item === 'table_inner_submit' && (spzt !== '-1' || djzt === '-1' || djzt === '0')) {
                            return false;
                        } else if (item === 'table_inner_retrieve' && !(djzt === '1' && spzt === '3')) {
                            return false;
                        } else if (item === 'table_inner_delete' && (spzt !== '-1' || djzt === '-1')) {
                            return false;
                        } else if (
                            item === 'table_inner_copy' &&
                            (red_status === '1' || tradeType.startsWith('2647'))
                        ) {
                            return false;
                        }
                        return true;
                    }),
                    {
                        area: config.innerButtonArea,
                        buttonLimit: 5,
                        onButtonClick: (props, key) => {
                            onTableInnerButtonClick.call(this, props, key, text, record, index);
                        }
                    }
                );
            }
        });
        props.meta.setMeta(meta, () => {
            this.initPage();
        });
    }

    setButton(button) {
        const props = this.props;
        props.button.setButtons(button);

        props.button.setPopContent({
            table_inner_submit: this.state.multiLang['confirm_submit_select'],
            table_inner_retrieve: this.state.multiLang['confirm_retrieve_select'],
            table_inner_delete: this.state.multiLang['confirm_delete_select']
        });
    }

    initPage() {
        const props = this.props;
        props.table.setTableRender(config.bodycode, 'djbh', (text, record) => {
            return (
                <a
                    // className="hyperlinks"
                    onClick={() => {
                        api.getBillLinkInfo({
                            openbillid: _.get(record, 'pk_jkbx.value'),
                            tradetype: _.get(record, 'djlxbm.value')
                        }).then(res => {
                            if (!res || !res.url) {
                                toast({
                                    color: 'warning',
                                    content: this.state.multiLang['bad_request']
                                }); /* 国际化处理： 参数错误*/
                                return;
                            }
                            props.specialOpenTo(res.url, {
                                status: 'browse',
                                id: res.openbillid,
                                tradetype: res.tradetype,
                                appcode: res.appcode,
                                pagecode: res.pagecode,
                                scene: 'bz'
                            });
                        });
                    }}
                >
                    {_.get(record, 'djbh.value')}
                </a>
            );
        });
        this.setPageStatus();

        // props.search.setSearchValByField(config.headcode, 'djrq', {
        //     value: '#week(0)#,#week(0)#'
        // });
    }

    setPageStatus() {
        const props = this.props;
        props.button.setButtonDisabled(['link', 'print', 'export'], true);
        props.table.selectAllRows(config.bodycode, false);
    }

    loadData(isFromSearch) {
        const props = this.props;
        const meta = props.meta.getMeta();
        const pageInfo = props.table.getTablePageInfo(config.bodycode);
        const query = props.search.getAllSearchData(config.headcode);

        const params = {
            appcode: config.appcode,
            pagecode: config.pagecode,
            queryAreaCode: config.headcode,
            querytype: 'tree',
            querycondition: query,
            oid: meta[config.headcode].oid,
            tradetype: this.state.tradeType,
            pageInfo: {
                pageIndex: pageInfo.pageIndex,
                pageSize: isFromSearch ? config.pageSize : pageInfo.pageSize
            }
        };

        return api.getBillList(params).then(res => {
            // 按钮初始化
            if (isFromSearch) {
                const total = Number(_.get(res, 'pageInfo.total', 0));
                if (total === 0) {
                    toast({
                        color: 'warning',
                        content: this.state.multiLang['query_none_message']
                    }); /* 国际化处理： 未查询出符合条件的数据*/
                } else {
                    toast({
                        color: 'success',
                        content: this.state.multiLang['query_total_message'].replace('{count}', total)
                    }); /* 国际化处理： 查询成功，共*条*/
                }
            } else {
                toast({
                    color: 'success',
                    content: this.state.multiLang['query_success']
                }); /* 国际化处理： 查询成功*/
            }

            this.setData(res);
        });
    }

    setData(res) {
        const props = this.props;
        const pageInfo = _.get(res, `pageInfo`, {});
        const data = {
            rows: _.get(res, `data.${config.bodycode}.rows`, []),
            pageInfo: pageInfo
        };
        if (pageInfo.pageIndex == 0) {
            data.allpks = new Array(Number(pageInfo.total));
        }
        props.table.setAllTableData(config.bodycode, data);
    }

    onCopyBill(record) {
        const { props } = this;
        const billId = _.get(record, 'pk_jkbx.value', '');
        const tradeType = _.get(record, 'pk_billtype.value', '');
        api.checkBillCopyStatus({
            openbillid: billId,
            pk_billtype: tradeType
        }).then(() => {
            api.getBillLinkInfo({
                openbillid: billId,
                tradetype: tradeType
            }).then(res => {
                props.specialOpenTo(res.url, {
                    status: 'add',
                    copyFromBillId: res.openbillid,
                    tradetype: res.tradetype,
                    appcode: res.appcode,
                    pagecode: res.pagecode
                });
            });
        });
    }

    onEditBill(record) {
        const { props } = this;
        api.getBillLinkInfo({
            openbillid: _.get(record, 'pk_jkbx.value', ''),
            tradetype: _.get(record, 'pk_billtype.value', '')
        }).then(res => {
            props.specialOpenTo(res.url, {
                status: 'edit',
                id: res.openbillid,
                tradetype: res.tradetype,
                appcode: res.appcode,
                pagecode: res.pagecode
            });
        });
    }

    submitBill() {
        const params = getDefData('submit', config.cache);
        if (!params) {
            console.error('提交流程数据异常');
            return;
        }
        const userjson = {
            openbillid: params.openbillid,
            fromssc: 'ssc',
            jkCheck: params.jkCheck,
            ntbCheck: params.ntbCheck,
            proBudgetCheck: params.proBudgetCheck,
            msg_pk_bill: '',
            pk_tradetype: params.tradetype,
            pagecode: params.pagecode,
            appcode: params.appcode,
            assingUsers: params.assingUsers,
            status: 'browse'
        };

        api.submitBill({
            openbillid: params.openbillid,
            pk_billtype: params.tradetype,
            djlxbm: params.djlxbm,
            userjson: JSON.stringify(userjson)
        }).then(res => {
            if (
                res.workflow &&
                res.billid &&
                res.bill &&
                (res.workflow == 'approveflow' || res.workflow == 'workflow')
            ) {
                this.setState({
                    isApprovalTransShowed: true,
                    approvalTransSourceData: res
                });
                return;
            }

            if (_.get(res, 'Alarm') === 'Y') {
                promptBox({
                    color: 'danger', // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                    title: this.state.multiLang['budget_control_reminder'], // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输
                    content: res.message, // 提示内容,非必输
                    beSureBtnClick: () => {
                        if (res.AlarmType && res.AlarmType == 'Project') {
                            setDefData('submit', config.cache, {
                                ...params,
                                proBudgetCheck: 'true'
                            });
                        } else {
                            setDefData('submit', config.cache, {
                                ...params,
                                ntbCheck: 'true'
                            });
                        }
                        this.submitBill();
                    },
                    cancelBtnClick: () => {
                        this.resetSubmitState();
                    }
                });
                return;
            }
            if (res.userjson) {
                let reimmsg = '';
                try {
                    reimmsg = _.get(JSON.parse(res.userjson), 'reimmsg');
                } catch (err) {
                    console.error(err);
                }
                if (!reimmsg) return;

                promptBox({
                    color: 'warning', // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                    content: reimmsg,
                    noCancelBtn: true // 是否显示取消按钮,，默认显示(false),非必输
                });
                return;
            }
            this.resetSubmitState();
            // this.props.table.updateDataByIndexs(config.bodycode, [
            //     { index: params.index, data: _.get(res, 'list.rows[0].values', {}) }
            // ]);
            this.props.table.setValByKeyAndIndex(
                config.bodycode,
                params.index,
                'spzt',
                _.get(res, 'list.rows[0].values.spzt', {})
            );
            this.forceUpdate();
            toast({
                color: 'success',
                content: this.state.multiLang['submit_success']
            }); /* 国际化处理： 查询成功*/
        });
    }

    resetSubmitState() {
        this.setState({
            isApprovalTransShowed: false
        });
        setDefData('submit', config.cache);
    }

    onApprovalTransOk(user) {
        const params = getDefData('submit', config.cache);
        setDefData('submit', config.cache, {
            ...params,
            assingUsers: user
        });
        this.setState({
            isApprovalTransShowed: false
        });
        this.submitBill();
    }

    onApprovalTransCancel() {
        this.resetSubmitState();
    }

    onSubmitBill(record, index) {
        const { props } = this;
        // console.log('====', getDefData(billId, config.cache));
        // debugger
        if (getDefData('submit', config.cache)) {
            setDefData('submit', config.cache);
        }
        const tradetype = _.get(record, 'pk_billtype.value', '');
        api.getBillLinkInfo({
            tradetype,
            openbillid: _.get(record, 'pk_jkbx.value', '')
        }).then(res => {
            setDefData('submit', config.cache, {
                tradetype,
                index: index,
                jkCheck: 'false',
                ntbCheck: 'false',
                proBudgetCheck: 'false',
                assingUsers: [],
                openbillid: res.openbillid,
                appcode: res.appcode,
                pagecode: res.pagecode,
                djlxbm: _.get(record, 'djlxbm.value', '')
            });
            this.submitBill();
        });
        // let;
    }

    onDeleteBill(record, index) {
        const { table } = this.props;
        api.deleteBill({
            openbillid: _.get(record, 'pk_jkbx.value', ''),
            pk_billtype: _.get(record, 'pk_billtype.value', '')
        }).then(res => {
            table.deleteTableRowsByIndex(config.bodycode, index);
            toast({
                color: 'success',
                content: this.state.multiLang['delete_success']
            }); /* 国际化处理： 查询成功*/
        });
    }

    onRetrieveBill(record, index) {
        api.retrieveBill({
            openbillid: _.get(record, 'pk_jkbx.value', ''),
            pk_billtype: _.get(record, 'pk_billtype.value', '')
        }).then(res => {
            // this.props.table.updateDataByIndexs(config.bodycode, [
            //     { index: index, data: _.get(res, 'list.rows[0].values', {}) }
            // ]);
            this.props.table.setValByKeyAndIndex(
                config.bodycode,
                index,
                'spzt',
                _.get(res, 'list.rows[0].values.spzt', {})
            );
            this.forceUpdate();
            toast({
                color: 'success',
                content: this.state.multiLang['retrieve_success']
            }); /* 国际化处理： 查询成功*/
        });
    }

    render() {
        const { table, button, search, modal, BillHeadInfo } = this.props;
        const { NCCreateSearch } = search;
        const { createBillHeadInfo } = BillHeadInfo;
        const { createSimpleTable } = table;

        return (
            <div className="nc-single-table">
                <div className="nc-singleTable-header-area">
                    <div className="header-title-search-area">
                        {createBillHeadInfo({
                            title: this.state.tradeTypeName,
                            initShowBackBtn: false
                        })}
                    </div>
                    <div className="header-button-area">
                        {button.createButtonApp({
                            area: config.pageButtonArea,
                            buttonLimit: 8,
                            onButtonClick: onPageButtonClick.bind(this)
                        })}
                    </div>
                </div>
                <div className="nc-singleTable-search-area">
                    {NCCreateSearch(config.headcode, { clickSearchBtn: onSearchButtonClick.bind(this) })}
                </div>
                <div className="nc-singleTable-table-area">
                    {createSimpleTable(config.bodycode, {
                        onRowDoubleClick: onTableRowDoubleClick.bind(this),
                        handlePageInfoChange: onTablePageChange.bind(this),
                        selectedChange: onTableSelectChange.bind(this),
                        showIndex: true,
                        showCheck: true
                    })}
                </div>

                {/* 审批指派 */}
                {this.state.isApprovalTransShowed && (
                    <ApprovalTrans
                        title={this.state.multiLang['assignment']}
                        data={this.state.approvalTransSourceData}
                        display={this.state.isApprovalTransShowed}
                        getResult={this.onApprovalTransOk.bind(this)}
                        cancel={this.onApprovalTransCancel.bind(this)}
                    />
                )}
            </div>
        );
    }
}

export default createPage({
    // billinfo: {
    //     billtype: 'grid',
    //     pagecode: config.pagecode,
    //     headcode: config.headcode
    // },
    mutiLangCode: config.mutiLangCode,
    initTemplate: null
})(Page);
